﻿#include "CharmedSnake.h"
#include "../../MirEnvir/Envir.h"
#include "../../MirEnvir/Map.h"
#include "../../../Shared/Enums.h"
#include "../../../Shared/Functions/Functions.h"
#include "../../../Shared/ServerPackets.h"
#include "../../../Shared/Data/Stat.h"

using namespace Server::MirDatabase;
using namespace Server::MirEnvir;
namespace S = ServerPackets;

namespace Server::MirObjects::Monsters
{

    CharmedSnake::CharmedSnake(MonsterInfo *info) : MonsterObject(info)
    {
        ActionTime = getEnvir()->getTime() + 1000;
    }

    std::string CharmedSnake::getName() const
    {
        return Master == nullptr ? Info->getGameName() : (Dead ? Info->getGameName() : StringHelper::formatSimple("{0}({1})", Info->getGameName(), Master->getName()));
    }

    void CharmedSnake::setName(const std::string &value)
    {
        throw NotSupportedException();
    }

    void CharmedSnake::Process()
    {
        if (!Dead && Summoned)
        {
            bool selfDestruct = false;
            if (Master != nullptr)
            {
                if (FindObject(Master->ObjectID, 15) == nullptr)
                {
                    selfDestruct = true;
                }
                if (Summoned && getEnvir()->getTime() > AliveTime)
                {
                    selfDestruct = true;
                }
                if (selfDestruct && Master != nullptr)
                {
                    Die();
                }
            }
        }
        MonsterObject::Process();
    }

    void CharmedSnake::Process(DelayedAction *action)
    {
        switch (action->Type)
        {
            case DelayedType::Damage:
                CompleteAttack(action->Params);
                break;
        }
    }

    void CharmedSnake::ProcessAI()
    {
        if (Dead)
        {
            return;
        }

        ProcessSearch();
        //todo ProcessRoaming(); needs no master follow just target roaming
        ProcessTarget();
    }

    void CharmedSnake::ProcessSearch()
    {
        if (getEnvir()->getTime() < SearchTime)
        {
            return;
        }
        SearchTime = getEnvir()->getTime() + SearchDelay;

        //Stacking or Infront of master - Move
        bool stacking = false;

        Cell *cell = getCurrentMap()->GetCell(getCurrentLocation());

        if (!cell->Objects.empty())
        {
            for (int i = 0; i < cell->Objects.size(); i++)
            {
                MapObject *ob = cell->Objects[i];
                if (ob == this || !ob->getBlocking())
                {
                    continue;
                }
                stacking = true;
                break;
            }
        }

        if (getCanMove() && ((MasterTotem != nullptr && MasterTotem->getFront() == getCurrentLocation()) || stacking))
        {
            //Walk Randomly
            if (!Walk(getDirection()))
            {
                MirDirection dir = getDirection();

                switch (getEnvir()->Random->Next(3)) // favour Clockwise
                {
                    case 0:
                        for (int i = 0; i < 7; i++)
                        {
                            dir = Functions::NextDir(dir);

                            if (Walk(dir))
                            {
                                break;
                            }
                        }
                        break;
                    default:
                        for (int i = 0; i < 7; i++)
                        {
                            dir = Functions::PreviousDir(dir);

                            if (Walk(dir))
                            {
                                break;
                            }
                        }
                        break;
                }
            }
        }

        if (getTarget() == nullptr || getEnvir()->Random->Next(3) == 0)
        {
            FindTarget();
        }
    }

    void CharmedSnake::ProcessRoam()
    {
        if (getTarget() != nullptr || getEnvir()->getTime() < RoamTime)
        {
            return;
        }

        if (ProcessRoute())
        {
            return;
        }

        if (MasterTotem != nullptr)
        {
            MoveTo(MasterTotem->getBack());
            return;
        }

        RoamTime = getEnvir()->getTime() + RoamDelay;
        if (getEnvir()->Random->Next(10) != 0)
        {
            return;
        }

        switch (getEnvir()->Random->Next(3)) //Face Walk
        {
            case 0:
                Turn(static_cast<MirDirection>(getEnvir()->Random->Next(8)));
                break;
            default:
                Walk(getDirection());
                break;
        }
    }

    void CharmedSnake::ProcessTarget()
    {
        if (getTarget() == nullptr || !getCanAttack())
        {
            return;
        }

        if (InAttackRange())
        {
            Attack();
            if (getTarget()->Dead)
            {
                FindTarget();
            }

            return;
        }

        if (getEnvir()->getTime() < ShockTime)
        {
            setTarget(nullptr);
            return;
        }

        MoveTo(getTarget()->getCurrentLocation());
    }

    void CharmedSnake::Attack()
    {
        if (!getTarget()->IsAttackTarget(this))
        {
            setTarget(nullptr);
            return;
        }

        setDirection(Functions::DirectionFromPoint(getCurrentLocation(), getTarget()->getCurrentLocation()));
        S::ObjectAttack *tempVar = new S::ObjectAttack();
        tempVar->ObjectID = ObjectID;
        tempVar->Direction = getDirection();
        tempVar->Location = getCurrentLocation();
        Broadcast(tempVar);

        int damage = GetAttackPower(Stats[Stat::MinDC], Stats[Stat::MaxDC]);
        if (damage > 0)
        {
            DelayedAction *action = new DelayedAction(DelayedType::Damage, getEnvir()->getTime() + 300, {getTarget(), damage, DefenceType::MAC});
            ActionList.push_back(action);

//C# TO C++ CONVERTER TODO TASK: A 'delete action' statement was not added since action was passed to a method or constructor. Handle memory management manually.
        }

        ActionTime = getEnvir()->getTime() + 300;
        AttackTime = getEnvir()->getTime() + AttackSpeed;
        ShockTime = 0;

//C# TO C++ CONVERTER TODO TASK: A 'delete tempVar' statement was not added since tempVar was passed to a method or constructor. Handle memory management manually.
    }

    void CharmedSnake::CompleteAttack(std::vector<std::any> &data)
    {
        MapObject *target = std::any_cast<MapObject*>(data[0]);
        int damage = std::any_cast<int>(data[1]);
        DefenceType defence = std::any_cast<DefenceType>(data[2]);

        if (target == nullptr || !target->IsAttackTarget(this) || target->getCurrentMap() != getCurrentMap() || target->Node == nullptr)
        {
            return;
        }

        if (target->Attacked(this, damage, defence) <= 0)
        {
            return;
        }

        PoisonTarget(target, 10 - PetLevel, 4 + PetLevel, PoisonType::Paralysis, 1000);
    }

    void CharmedSnake::Die()
    {
        MonsterObject::Die();

        //Explosion
        for (int y = getCurrentLocation()->Y - 1; y <= getCurrentLocation()->Y + 1; y++)
        {
            if (y < 0)
            {
                continue;
            }
            if (y >= getCurrentMap()->Height)
            {
                break;
            }

            for (int x = getCurrentLocation()->X - 1; x <= getCurrentLocation()->X + 1; x++)
            {
                if (x < 0)
                {
                    continue;
                }
                if (x >= getCurrentMap()->Width)
                {
                    break;
                }

                Cell *cell = getCurrentMap()->GetCell(x, y);

                if (!cell->getValid() || cell->Objects.empty())
                {
                    continue;
                }

                for (int i = 0; i < cell->Objects.size(); i++)
                {
                    MapObject *target = cell->Objects[i];
                    switch (target->getRace())
                    {
                        case ObjectType::Monster:
                        case ObjectType::Player:
                            //Only targets
                            if (!target->IsAttackTarget(this) || target->Dead)
                            {
                                break;
                            }
                            target->Attacked(this, 10 * PetLevel, DefenceType::MACAgility);
                            break;
                    }
                }
            }
        }
    }

    void CharmedSnake::Spawned()
    {
        MonsterObject::Spawned();
        Summoned = true;
    }

    Packet *CharmedSnake::GetInfo()
    {
        S::ObjectMonster *tempVar = new S::ObjectMonster();
        tempVar->ObjectID = ObjectID;
        tempVar->Name = getName();
        tempVar->NameColour = NameColour;
        tempVar->Location = getCurrentLocation();
        tempVar->Image = Monster::CharmedSnake;
        tempVar->Direction = getDirection();
        tempVar->Effect = Info->Effect;
        tempVar->AI = Info->AI;
        tempVar->Light = Info->Light;
        tempVar->Dead = Dead;
        tempVar->Skeleton = Harvested;
        tempVar->Poison = CurrentPoison;
        tempVar->Hidden = getHidden();
        tempVar->Extra = Summoned;

//C# TO C++ CONVERTER TODO TASK: A 'delete tempVar' statement was not added since tempVar was used in a 'return' or 'throw' statement.
        return tempVar;
    }
}
